package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"sync"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

// 用户结构体
type User struct {
	ID   string
	Conn *websocket.Conn
}

// 用户管理器
type UserManager struct {
	sync.Mutex
	Users map[string]*User
}

var userManager = UserManager{
	Users: make(map[string]*User),
}

// 用户登录
func login(c *gin.Context) {
	userID := c.Query("userID")

	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "升级连接失败"})
		return
	}

	user := &User{
		ID:   userID,
		Conn: conn,
	}

	userManager.Lock()
	userManager.Users[userID] = user
	userManager.Unlock()

	// 处理WebSocket通信
	go handleWebSocket(user)
}

// 接受发送过来json数据
type MyData struct {
	Touser string `json:"touser"`
	Msg    string `json:"msg"`
}

// 处理WebSocket通信
func handleWebSocket(user *User) {
	defer user.Conn.Close()

	for {
		messageType, p, err := user.Conn.ReadMessage()
		// fmt.Println(messageType)
		if err != nil {
			// 用户下线
			userManager.Lock()
			delete(userManager.Users, user.ID)
			userManager.Unlock()
			break
		}

		//解析json数据
		var data MyData
		if err := json.Unmarshal(p, &data); err != nil {
			fmt.Printf("解析json错误: %v", err)
		}

		// 广播消息
		userManager.Lock()
		for _, u := range userManager.Users {
			if u.ID == data.Touser {
				err = u.Conn.WriteMessage(messageType, p)
				if err != nil {
					// 处理错误
				}
			}
		}
		userManager.Unlock()
	}
}

func main() {
	r := gin.Default()
	r.GET("/login", login)
	r.Run(":8080")
}
